package com.starblink.store.memanage.ui

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.RemoveStoresEvent
import com.starblink.android.basic.util.bus.bean.SubscribeBrandEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.common.view.brand.BrandRecommendResultCell
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.rocketreserver.fragment.BrandVOF
import com.starblink.store.databinding.ActivityNewManageStoreBinding
import com.starblink.store.databinding.ItemMemanageBrandBinding
import com.starblink.store.databinding.ItemMineManageEmptyBinding
import com.starblink.store.databinding.ItemMineManageTitleBinding
import com.starblink.store.memanage.adapter.ManageStoreEmptyCell
import com.starblink.store.memanage.adapter.ManageTitleCell
import com.starblink.store.memanage.adapter.SubBrandCell
import com.starblink.store.memanage.vm.ManageBrandVM

@Route(path = RoutePage.Store.PAGE_MANAGE_BRAND)
class NewManageBrandActivity : BaseTVMActivity<ActivityNewManageStoreBinding, ManageBrandVM>() {

    @Autowired(name = RoutePage.Store.FOLLOWED)
    @JvmField
    var hasFollowedStore: Boolean = false //是否有订阅

    override fun initViewBinding(): ActivityNewManageStoreBinding =
        ActivityNewManageStoreBinding.inflate(layoutInflater)

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.list.value!!).apply {
            addVhDelegate {
                SubBrandCell(
                    ItemMemanageBrandBinding.inflate(it.inflater, it, false),
                    { position, merchantWebVOF ->
                        navigationTo(RoutePage.Brand.BRAND_DETAIL) {
                            withString(
                                RoutePage.Brand.ARG_BRAND_ID,
                                merchantWebVOF.brandId.toString()
                            )
                            withBoolean(
                                RoutePage.Brand.ARG_IS_DISCOUNT_BRAND,
                                merchantWebVOF.brandDiscount != null
                            )
                        }
                        if (merchantWebVOF.read == false) {
                            viewModel.readMessage(position, merchantWebVOF)
                            ApolloValSetExt.setApolloVal<BrandVOF>(
                                merchantWebVOF, "read",
                                true
                            )
                            adapter.notifyDataSetChanged()
                        }
                    }, { position, merchant ->
                        viewModel.removeItem(position)
                    })
            }
            addVhDelegate {
                BrandRecommendResultCell(
                    SpmPageDef.MeBrandSubListPage,
                    viewGroup = it,
                ) { merchant, position ->
                    merchant.brandId?.let { it1 ->
                        CommonMutateManage.subscribeOrNotBrand(
                            this@NewManageBrandActivity, merchant.hasSub,
                            it1, brand = merchant,
                            resultCallback = {
                                ApolloValSetExt.setApolloVal<BrandVOF>(
                                    merchant, "hasSub",
                                    !merchant.hasSub
                                )
                                ApolloValSetExt.setApolloVal<BrandVOF>(
                                    merchant, "subNums",
                                    if (merchant.hasSub) (merchant.subNums!! + 1) else (merchant.subNums!! - 1)
                                )
                                refreshItem(position)
                            }
                        )
                    }
                }
            }
            addVhDelegate {
                //my service标题
                ManageTitleCell(
                    ItemMineManageTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                ManageStoreEmptyCell(
                    ItemMineManageEmptyBinding.inflate(it.inflater, it, false)
                )
            }
        }
    }

    private fun refreshItem(position: Int) {
        adapter.notifyItemChanged(position)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarBlackText()
//        if (hasFollowedStore) {
        viewModel.fetchMySubscribeMerchantWeb(true, false)
//        } else {
//            viewModel.addEmptyView()
//        }

        viewModel.list.observe(this) {
            if (viewBinding.recyclerView.adapter == null) {
                viewBinding.recyclerView.adapter = adapter//单位px
            } else {
                adapter.notifyDataSetChanged()
            }
        }


        flowData()
    }

    override fun initView() {
        super.initView()
        viewBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null

//        viewBinding.recyclerView.addItemDecoration(DefaultDecoration(this).apply {
//            startVisible = true
//            endVisible = true
//            this.setDivider(12.dp2px())
//        })

        viewBinding.refresher.setEnableLoadMore(true)
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setOnLoadMoreListener {
            if (viewModel.loadedRecommend) {
                viewModel.loadRecommendStores()
            } else {
                viewModel.fetchMySubscribeMerchantWeb(false, false)
            }
            viewBinding.refresher.finishLoadMore(5000)
        }
        viewBinding.title.title = "Manage My Brands"
        viewBinding.title.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }

            override fun onRightClick(titleBar: TitleBar?) {
                navigationTo(RoutePage.Store.PAGE_MANAGE) {
                    withBoolean(RoutePage.Store.IS_BRAND, true)
                }
            }
        })
        FontUtil.setMontseratSemiBold(viewBinding.title.titleView)

        viewBinding.llSearch.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.BRANDS.value)
            }
        }
    }


    /**
     * 同步订阅数据
     */
    private fun flowData() {
        FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT).register(this) {
            if (it.brandId != null) {
                if (it.hasSub) {
                    if (it.brand != null) {
                        viewModel.addSubscribeStore(it.brand!!)
                    } else {
                        viewModel.fetchMySubscribeMerchantWeb(
                            showLoading = false,
                            initRefresh = true
                        )
                    }
                } else {
                    for ((index, post) in viewModel.list.value!!.withIndex()) {
                        if (post != null && post is BrandVOF && it.brandId == post.brandId) {
                            viewModel.removeItem(index)
                            break
                        }
                    }
                }
            }
        }

        //同步取消店铺
        FlowBus.with<RemoveStoresEvent>(FlowConst.REMOVE_STORE_EVENT).register(this) {
            if (it.ids != null) {
                var removed = false
                for (id in it.ids!!) {
                    val first = viewModel.list.value!!.indexOfFirst {
                        it is BrandVOF && it.brandId.toString() == id
                    }
                    viewModel.list.value!!.removeAt(first)
                    removed = true

                    refreshRecommendListSub(id, false)
                }
                if (removed) {
                    viewModel.list.value = viewModel.list.value
                }
            }
        }

        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.fetchMySubscribeMerchantWeb(showLoading = false, initRefresh = true)
        }
    }

    private fun refreshRecommendListSub(id: String, sub: Boolean) {
        //刷新推荐列表订阅状态
        val index =
            viewModel.list.value!!.indexOfFirst { it is BrandVOF && it.brandId.toString() == id }
        if (index >= 0) {
            val merchant = viewModel.list.value!![index]
            if (merchant is BrandVOF && merchant.hasSub != sub) {
                ApolloValSetExt.setApolloVal<BrandVOF>(merchant, "hasSub", sub)
                viewModel.list.value!![index] = merchant
            }
            viewModel.list.value = viewModel.list.value
        }
    }


    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.MeBrandSubListPage)
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.MeBrandSubListPage)
    }
}